package com.xcjh.utils;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  复制集合的工具类
 * </p>
 *
 * @author:bood
 * @date:2021/12/2
 */
public class CopyListUtil {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        List<Integer> i = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        List<? extends List> lists = copyList2(list, i.getClass());
        System.out.println(lists);
    }
    /**
     * 删除集合中重复的元素
     * @param source
     * @param target
     * @return
     */
    public static List<Long> removeSame(List<Long> source, List<Long> target){
        HashSet<Long> set = new HashSet<>(source);
        target.removeAll(set);
        return target;
    }
    /**
     * 从List<A>到List<B>
     *
     * @param list
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> copyList1(List<?> list, Class<T> clazz) {
        return JSON.parseArray(JSON.toJSONString(list), clazz);
    }

    /**
     * 从List<A>到List<B>
     *
     * @param list
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> copyList2(List<?> list, Class<T> clazz) {
        List<T> result = new ArrayList<>(list.size());
        for (Object source : list) {
            T target;
            try {
                target = clazz.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                throw new RuntimeException();
            }
            BeanUtils.copyProperties(source, target);
            result.add(target);
        }
        return result;
    }

    /**
     * 从List<A>到List<B>
     *
     * @param list
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> copyList3(List<?> list, Class<T> clazz) {
        return (List) list.stream().map((source) -> {
            Object target = null;
            try {
                target = clazz.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
            BeanUtil.copyProperties(source, target);
            return target;
        }).collect(Collectors.toList());
    }
}
